package com.wei.spring.web.user.filter;

import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;
import org.springframework.web.util.WebUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Objects;

/**
 * 打印Http请求和响应的日志过滤器
 *
 * @author buhuan.wang
 * @since 2020/12/30
 */
@Slf4j
@WebFilter
public class HttpTraceLogFilter extends OncePerRequestFilter implements Ordered {

    private static final String NEED_TRACE_PATH_PREFIX = "/";
    private static final String IGNORE_REQUEST_BODY_CONTENT_TYPE = "multipart/form-data";

    public HttpTraceLogFilter() {
    }


    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE - 10;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        if (!isRequestValid(request)) {
            filterChain.doFilter(request, response);
            return;
        }
        if (!(request instanceof ContentCachingRequestWrapper)) {
            request = new ContentCachingRequestWrapper(request);
        }
        if (!(response instanceof ContentCachingResponseWrapper)) {
            response = new ContentCachingResponseWrapper(response);
        }
        int status = HttpStatus.INTERNAL_SERVER_ERROR.value();
        long startTime = System.currentTimeMillis();
        try {
            filterChain.doFilter(request, response);
            status = response.getStatus();
        } finally {
            String path = request.getRequestURI();
            if (path.startsWith(NEED_TRACE_PATH_PREFIX)) {
                // 记录日志
                HttpTraceLog traceLog = new HttpTraceLog();
                traceLog.setUri(path);
                traceLog.setMethod(request.getMethod());
                long latency = System.currentTimeMillis() - startTime;
                traceLog.setTimeTaken(latency);
                traceLog.setStartTime(startTime);
                traceLog.setParameterMap(JSON.toJSONString(request.getParameterMap()));
                traceLog.setStatusCode(status);
                logRequestBody(traceLog, request);
                traceLog.setResponseBody(getResponseBody(response));
                if (log.isInfoEnabled()) {
                    log.info("Http trace log: {}", JSON.toJSONString(traceLog));
                }
            }
            updateResponse(response);
        }
    }

    private void logRequestBody(HttpTraceLog traceLog, HttpServletRequest request) throws IOException {
        if (StringUtils.isEmpty(request.getContentType())
                || !request.getContentType().contains(IGNORE_REQUEST_BODY_CONTENT_TYPE)) {
            String requestBody = getRequestBody(request);
            if (StringUtils.isBlank(requestBody)) {
                requestBody = IOUtils.toString(request.getInputStream(), Charsets.UTF_8);
            }
            traceLog.setRequestBody(requestBody);
        }
    }

    private boolean isRequestValid(HttpServletRequest request) {
        try {
            new URI(request.getRequestURL().toString());
            return true;
        } catch (URISyntaxException ex) {
            return false;
        }
    }

    private String getRequestBody(HttpServletRequest request) {
        String requestBody = "";
        ContentCachingRequestWrapper wrapper = WebUtils.getNativeRequest(request, ContentCachingRequestWrapper.class);
        if (wrapper != null) {
            try {
                requestBody = IOUtils.toString(wrapper.getContentAsByteArray(), wrapper.getCharacterEncoding());
            } catch (IOException e) {
                log.error("getRequestBody error!", e);
            }
        }
        return requestBody;
    }

    private String getResponseBody(HttpServletResponse response) {
        String responseBody = "";
        ContentCachingResponseWrapper wrapper = WebUtils.getNativeResponse(response, ContentCachingResponseWrapper.class);
        if (wrapper != null) {
            try {
                responseBody = IOUtils.toString(wrapper.getContentAsByteArray(), wrapper.getCharacterEncoding());
            } catch (IOException e) {
                log.error("getResponseBody error!", e);
            }
        }
        return responseBody;
    }

    private void updateResponse(HttpServletResponse response) throws IOException {
        ContentCachingResponseWrapper responseWrapper = WebUtils.getNativeResponse(response, ContentCachingResponseWrapper.class);
        Objects.requireNonNull(responseWrapper).copyBodyToResponse();
    }


    @Data
    public static class HttpTraceLog {

        private String uri;
        private String parameterMap;
        private String method;
        private Long timeTaken;
        private Long startTime;
        private Integer statusCode;
        private String requestBody;
        private String responseBody;
    }

}
